package com.xingxing.Util;

import com.xingxing.Bean.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class CommonsUtils {

    public static String makeRanddomNum(int numLen) {
        Random random = new Random();
        String num = random.nextInt(10000) + "";
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < numLen - num.length(); i++) {
            stringBuffer.append("0");
        }
        num = stringBuffer.toString() + num;
        return num;
    }

    public static String getCurrentTime() {
        return new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒").format(new Date());
    }

    public static String saveFileForUser(User user, FileItem fileItem) throws IOException {
        String filename = fileItem.getName();// 获取上传的文件名
        //处理上传文件
        if (filename != null && !filename.equals("")) {
            filename = filename.substring(filename.lastIndexOf("\\") + 1);// 截取出文件名
            filename = UUID.randomUUID().toString() + "_" + filename;// 文件名需要唯一
            Properties prams = CommonsUtils.getProperties("config.properties");
            String filepath = prams.getProperty("FileUpload")+user.getUserAccount()+"\\"+filename;
            File file = new File(filepath);// 创建文件
            file.getParentFile().mkdirs();
            file.createNewFile();
            InputStream in = fileItem.getInputStream();// 获得上传文件流
            FileOutputStream out = new FileOutputStream(file);// 使用FileOutputStream打开服务器端的上传文件

            byte[] buffer = new byte[1024];//每次读取1个字节
            int len;
            //开始读取上传文件的字节，并将其输出到服务端的上传文件输出流中
            while ((len = in.read(buffer)) > 0)
                out.write(buffer, 0, len);

            in.close();// 关闭流
            out.close();
            fileItem.delete();// 删除临时文件
        }
        return filename;
    }

    public static String saveFile(FileItem fileItem) throws IOException {
        String filename = fileItem.getName();// 获取上传的文件名
        //处理上传文件
        if (filename != null && !filename.equals("")) {
            filename = filename.substring(filename.lastIndexOf("\\") + 1);// 截取出文件名
            filename = UUID.randomUUID().toString() + "_" + filename;// 文件名需要唯一
            String filepath = "D:\\upload\\"+filename;
            File file = new File(filepath);// 创建文件
            file.getParentFile().mkdirs();
            file.createNewFile();
            InputStream in = fileItem.getInputStream();// 获得上传文件流
            FileOutputStream out = new FileOutputStream(file);// 使用FileOutputStream打开服务器端的上传文件

            byte[] buffer = new byte[1024];//每次读取1个字节
            int len;
            //开始读取上传文件的字节，并将其输出到服务端的上传文件输出流中
            while ((len = in.read(buffer)) > 0)
                out.write(buffer, 0, len);

            in.close();// 关闭流
            out.close();
            fileItem.delete();// 删除临时文件
//            writer.print("上传文件成功！<br>");
        }
        return filename;
    }

    public static List<FileItem> getFileItem(HttpServletRequest request) throws FileUploadException {
        Properties prams = CommonsUtils.getProperties("config.properties");
        File f = new File(prams.getProperty("FileTemp"));// 设置文件缓存目录，如果该目录不存在则新创建一个
        if (!f.exists()) {
            f.mkdirs();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();// 创建DiskFileItemFactory工厂对象
        factory.setRepository(f);// 设置文件的缓存路径
        ServletFileUpload fileupload = new ServletFileUpload(factory);// 创建 ServletFileUpload对象
        fileupload.setSizeMax(Integer.parseInt(prams.getProperty("FileSizeMax"))*1024);
        fileupload.setHeaderEncoding("utf-8");//设置字符编码
        return fileupload.parseRequest(request);
    }

    public static Properties getProperties(String fileName){
        Properties params=new Properties();
        InputStream is= CommonsUtils.class.getClassLoader().getResourceAsStream(fileName);
        try {
            params.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return params;
    }
}
